The course introduces some basic statistical analysis methods and open research tools to analyze data, and to document and share code and results. The course consists of seven weekly meetings with the following topics:
The course is organized online and is organized by Doctoral School in Humanities and Social Sciences.
I’m a PhD student in the University of Helsinki and the topic of my PhD thesis is Projections of Population Health Outcomes. I’m working at the Finnish Institute for Health and Welfare (THL) as a statistical researcher. I currently have a busy schedule but I was happy to squeeze this course into it although my supervisor told me about this course already a few years ago. I’m looking forward for participating in IODS and getting an overview about the tools used for documenting and sharing R-code.
The link to my GitHub repository.
In this week analysis we use JYTOPKYS2 dataset which contains survey variables related to students’ learning and teaching. The analysis dataset consists of 166 students and 7 variables. There are no missing values in the dataset. The dataset includes following variables:
#reading dataset
analysis_data <- read.csv(file='/home/jkox/Git/proj/IODS-project/data/learning2014.csv')
analysis_data$gender <- factor(analysis_data$gender) #setting gender as factor
dim(analysis_data) #the dimensions of the dataset
## [1] 166 7
str(analysis_data) #the structure of the dataset
## 'data.frame': 166 obs. of 7 variables:
## $ gender : Factor w/ 2 levels "F","M": 1 2 1 2 2 1 2 1 2 1 ...
## $ age : int 53 55 49 53 49 38 50 37 37 42 ...
## $ attitude: num 3.7 3.1 2.5 3.5 3.7 3.8 3.5 2.9 3.8 2.1 ...
## $ deep : num 3.58 2.92 3.5 3.5 3.67 ...
## $ stra : num 3.38 2.75 3.62 3.12 3.62 ...
## $ surf : num 2.58 3.17 2.25 2.25 2.83 ...
## $ points : int 25 12 24 10 22 21 21 31 24 26 ...
head(analysis_data,10) #the first 10 rows of the dataset
## gender age attitude deep stra surf points
## 1 F 53 3.7 3.583333 3.375 2.583333 25
## 2 M 55 3.1 2.916667 2.750 3.166667 12
## 3 F 49 2.5 3.500000 3.625 2.250000 24
## 4 M 53 3.5 3.500000 3.125 2.250000 10
## 5 M 49 3.7 3.666667 3.625 2.833333 22
## 6 F 38 3.8 4.750000 3.625 2.416667 21
## 7 M 50 3.5 3.833333 2.250 1.916667 21
## 8 F 37 2.9 3.250000 4.000 2.833333 31
## 9 M 37 3.8 4.333333 4.250 2.166667 24
## 10 F 42 2.1 4.000000 3.500 3.000000 26
There are 110 female and 56 male in the datasets. Theee seems to be no large differences in distributions of continuous variables by gender although the mean of attitude for male is larger than the mean for female. The distribution of age is right skewed. The distributions of other continuous variables are visually normal distributed. The largest positive correlation is between points and attitude, and largest negative correlation between surf and deep.
#graphical overview:
p <- ggpairs(analysis_data, mapping = aes(), lower = list(combo = wrap("facethist", bins = 20)))
p
summary(analysis_data) #basic summaries of the variables
## gender age attitude deep stra surf points
## F:110 Min. :17.00 Min. :1.400 Min. :1.583 Min. :1.250 Min. :1.583 Min. : 7.00
## M: 56 1st Qu.:21.00 1st Qu.:2.600 1st Qu.:3.333 1st Qu.:2.625 1st Qu.:2.417 1st Qu.:19.00
## Median :22.00 Median :3.200 Median :3.667 Median :3.188 Median :2.833 Median :23.00
## Mean :25.51 Mean :3.143 Mean :3.680 Mean :3.121 Mean :2.787 Mean :22.72
## 3rd Qu.:27.00 3rd Qu.:3.700 3rd Qu.:4.083 3rd Qu.:3.625 3rd Qu.:3.167 3rd Qu.:27.75
## Max. :55.00 Max. :5.000 Max. :4.917 Max. :5.000 Max. :4.333 Max. :33.00
Linear regression model is used to assess the relationship between target variable points and explanatory variables attitude, age and stra. The intercept of the model is statistically significant. The beta coefficients of attitude and stra are larger than zero meaning they are positively associated with points. On the contrary, age is negatively associated with points. However, t-test results show that only the relationship between points and attitude is statistically significant. This means that with the probability of 0.00025 the beta coefficient of attitude is zero (very unlikely). The beta coefficients of age and stra have p-values larger than 0.05 and are thus non-significant.
Since age is the variable with the largest p-value, linear model is fitted without it. In this second model the relationship between points and stra remains non-significant so a third model with only attitude as an explanatory variable is fitted. The intercept of the final model is 11.64 and the beta coefficient of attitude is 3.53. The intercept can be interpreted as the expected value of points when attitude equals zero. In addition, the beta coefficient of attitude is the expected increase in points when attitude increases by one unit. The multiple R squared of the final model is 0.19. This means that 19% of the variation in the data is explained by the final model.
my_model <- lm(points ~ attitude+age+stra, data = analysis_data) #model with attitude, age and stra
summary(my_model)
##
## Call:
## lm(formula = points ~ attitude + age + stra, data = analysis_data)
##
## Residuals:
## Min 1Q Median 3Q Max
## -18.1149 -3.2003 0.3303 3.4129 10.7599
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 10.89543 2.64834 4.114 6.17e-05 ***
## attitude 3.48077 0.56220 6.191 4.72e-09 ***
## age -0.08822 0.05302 -1.664 0.0981 .
## stra 1.00371 0.53434 1.878 0.0621 .
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 5.26 on 162 degrees of freedom
## Multiple R-squared: 0.2182, Adjusted R-squared: 0.2037
## F-statistic: 15.07 on 3 and 162 DF, p-value: 1.07e-08
my_model2 <- lm(points ~ attitude+stra, data = analysis_data) #model with attitude and stra
summary(my_model2)
##
## Call:
## lm(formula = points ~ attitude + stra, data = analysis_data)
##
## Residuals:
## Min 1Q Median 3Q Max
## -17.6436 -3.3113 0.5575 3.7928 10.9295
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 8.9729 2.3959 3.745 0.00025 ***
## attitude 3.4658 0.5652 6.132 6.31e-09 ***
## stra 0.9137 0.5345 1.709 0.08927 .
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 5.289 on 163 degrees of freedom
## Multiple R-squared: 0.2048, Adjusted R-squared: 0.1951
## F-statistic: 20.99 on 2 and 163 DF, p-value: 7.734e-09
my_model3 <- lm(points ~ attitude, data = analysis_data) #model with attitude
summary(my_model3)
##
## Call:
## lm(formula = points ~ attitude, data = analysis_data)
##
## Residuals:
## Min 1Q Median 3Q Max
## -16.9763 -3.2119 0.4339 4.1534 10.6645
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 11.6372 1.8303 6.358 1.95e-09 ***
## attitude 3.5255 0.5674 6.214 4.12e-09 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 5.32 on 164 degrees of freedom
## Multiple R-squared: 0.1906, Adjusted R-squared: 0.1856
## F-statistic: 38.61 on 1 and 164 DF, p-value: 4.119e-09
p <- qplot(attitude, points, data = analysis_data) + geom_smooth(method = "lm") #plot
p
## `geom_smooth()` using formula 'y ~ x'
Linear model makes several assumptions. These assumptions include that:
The validity of these assumptions should be checked when using linear regression. Also, the presence of influential values in the data should be checked.
The model diagnostic plots of the final model are presented below. Residuals vs. fitted plot can be used to check the assumptions 1 and 3. Now, a horizontal line is an indication for a linear relationship. However, there seems to be heteroscedasticity present since the spread of the residuals is not approximately the same across the x-axis. Normal Q-Q plot indicates that there seems to be a violation of assumption 2, since the residuals are not following the straight line at the ends of the line.
Residuals vs Leverage plot is used to check whether there are outliers or data points with high leverage. Outliers can be identified by examining the standardized residuals of data points. Cook’s distance measures the influence of the data points as a combination of leverage and residual size. Data points with three largest Cook’s distances are labelled in Residuals vs Leverage plot. There are no points outside the red dashed line so there are no influential data points.
par(mfrow=c(2,2))
plot(my_model3,1)
plot(my_model3,2)
plot(my_model3,5)
In this week analysis we use Student performance Data Set which contains information about student performance in mathematics and Portuguese language in secondary education of two Portuguese schools. The data attributes include student grades, demographic, social and school related features, and it was collected by using school reports and questionnaires. The analysis dataset consists of 370 students and 51 variables. The full description of dataset is available in here.
#reading dataset
pormath <- read.csv(file='/home/jkox/Git/proj/IODS-project/data/pormath.csv')
#names of the variables
names(pormath)
## [1] "school" "sex" "age" "address" "famsize" "Pstatus" "Medu" "Fedu"
## [9] "Mjob" "Fjob" "reason" "guardian" "traveltime" "studytime" "schoolsup" "famsup"
## [17] "activities" "nursery" "higher" "internet" "romantic" "famrel" "freetime" "goout"
## [25] "Dalc" "Walc" "health" "n" "id.p" "id.m" "failures" "paid"
## [33] "absences" "G1" "G2" "G3" "failures.p" "paid.p" "absences.p" "G1.p"
## [41] "G2.p" "G3.p" "failures.m" "paid.m" "absences.m" "G1.m" "G2.m" "G3.m"
## [49] "alc_use" "high_use" "cid"
dim(pormath) #the dimensions of the dataset
## [1] 370 51
str(pormath) #the structure of the dataset
## 'data.frame': 370 obs. of 51 variables:
## $ school : chr "GP" "GP" "GP" "GP" ...
## $ sex : chr "F" "F" "F" "F" ...
## $ age : int 15 15 15 15 15 15 15 15 15 15 ...
## $ address : chr "R" "R" "R" "R" ...
## $ famsize : chr "GT3" "GT3" "GT3" "GT3" ...
## $ Pstatus : chr "T" "T" "T" "T" ...
## $ Medu : int 1 1 2 2 3 3 3 2 3 3 ...
## $ Fedu : int 1 1 2 4 3 4 4 2 1 3 ...
## $ Mjob : chr "at_home" "other" "at_home" "services" ...
## $ Fjob : chr "other" "other" "other" "health" ...
## $ reason : chr "home" "reputation" "reputation" "course" ...
## $ guardian : chr "mother" "mother" "mother" "mother" ...
## $ traveltime: int 2 1 1 1 2 1 2 2 2 1 ...
## $ studytime : int 4 2 1 3 3 3 3 2 4 4 ...
## $ schoolsup : chr "yes" "yes" "yes" "yes" ...
## $ famsup : chr "yes" "yes" "yes" "yes" ...
## $ activities: chr "yes" "no" "yes" "yes" ...
## $ nursery : chr "yes" "no" "yes" "yes" ...
## $ higher : chr "yes" "yes" "yes" "yes" ...
## $ internet : chr "yes" "yes" "no" "yes" ...
## $ romantic : chr "no" "yes" "no" "no" ...
## $ famrel : int 3 3 4 4 4 4 4 4 4 4 ...
## $ freetime : int 1 3 3 3 2 3 2 1 4 3 ...
## $ goout : int 2 4 1 2 1 2 2 3 2 3 ...
## $ Dalc : int 1 2 1 1 2 1 2 1 2 1 ...
## $ Walc : int 1 4 1 1 3 1 2 3 3 1 ...
## $ health : int 1 5 2 5 3 5 5 4 3 4 ...
## $ n : int 2 2 2 2 2 2 2 2 2 2 ...
## $ id.p : int 1096 1073 1040 1025 1166 1039 1131 1069 1070 1106 ...
## $ id.m : int 2096 2073 2040 2025 2153 2039 2131 2069 2070 2106 ...
## $ failures : int 0 1 0 0 1 0 1 0 0 0 ...
## $ paid : chr "yes" "no" "no" "no" ...
## $ absences : int 3 2 8 2 5 2 0 1 9 10 ...
## $ G1 : int 10 10 14 10 12 12 11 10 16 10 ...
## $ G2 : int 12 8 13 10 12 12 6 10 16 10 ...
## $ G3 : int 12 8 12 9 12 12 6 10 16 10 ...
## $ failures.p: int 0 0 0 0 0 0 0 0 0 0 ...
## $ paid.p : chr "yes" "no" "no" "no" ...
## $ absences.p: int 4 2 8 2 2 2 0 0 6 10 ...
## $ G1.p : int 13 13 14 10 13 11 10 11 15 10 ...
## $ G2.p : int 13 11 13 11 13 12 11 10 15 10 ...
## $ G3.p : int 13 11 12 10 13 12 12 11 15 10 ...
## $ failures.m: int 1 2 0 0 2 0 2 0 0 0 ...
## $ paid.m : chr "yes" "no" "yes" "yes" ...
## $ absences.m: int 2 2 8 2 8 2 0 2 12 10 ...
## $ G1.m : int 7 8 14 10 10 12 12 8 16 10 ...
## $ G2.m : int 10 6 13 9 10 12 0 9 16 11 ...
## $ G3.m : int 10 5 13 8 10 11 0 8 16 11 ...
## $ alc_use : num 1 3 1 1 2.5 1 2 2 2.5 1 ...
## $ high_use : logi FALSE TRUE FALSE FALSE TRUE FALSE ...
## $ cid : int 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 ...
head(pormath,10) #the first 10 rows of the dataset
## school sex age address famsize Pstatus Medu Fedu Mjob Fjob reason guardian traveltime
## 1 GP F 15 R GT3 T 1 1 at_home other home mother 2
## 2 GP F 15 R GT3 T 1 1 other other reputation mother 1
## 3 GP F 15 R GT3 T 2 2 at_home other reputation mother 1
## 4 GP F 15 R GT3 T 2 4 services health course mother 1
## 5 GP F 15 R GT3 T 3 3 services services reputation other 2
## 6 GP F 15 R GT3 T 3 4 services health course mother 1
## 7 GP F 15 R GT3 T 3 4 services teacher course father 2
## 8 GP F 15 R LE3 T 2 2 health services reputation mother 2
## 9 GP F 15 R LE3 T 3 1 other other reputation father 2
## 10 GP F 15 U GT3 A 3 3 other health reputation father 1
## studytime schoolsup famsup activities nursery higher internet romantic famrel freetime goout Dalc Walc
## 1 4 yes yes yes yes yes yes no 3 1 2 1 1
## 2 2 yes yes no no yes yes yes 3 3 4 2 4
## 3 1 yes yes yes yes yes no no 4 3 1 1 1
## 4 3 yes yes yes yes yes yes no 4 3 2 1 1
## 5 3 no yes yes yes yes yes yes 4 2 1 2 3
## 6 3 yes yes yes yes yes yes no 4 3 2 1 1
## 7 3 no yes no yes yes yes yes 4 2 2 2 2
## 8 2 yes yes no yes yes yes no 4 1 3 1 3
## 9 4 no yes no no yes yes no 4 4 2 2 3
## 10 4 yes no no yes yes no no 4 3 3 1 1
## health n id.p id.m failures paid absences G1 G2 G3 failures.p paid.p absences.p G1.p G2.p G3.p failures.m
## 1 1 2 1096 2096 0 yes 3 10 12 12 0 yes 4 13 13 13 1
## 2 5 2 1073 2073 1 no 2 10 8 8 0 no 2 13 11 11 2
## 3 2 2 1040 2040 0 no 8 14 13 12 0 no 8 14 13 12 0
## 4 5 2 1025 2025 0 no 2 10 10 9 0 no 2 10 11 10 0
## 5 3 2 1166 2153 1 yes 5 12 12 12 0 yes 2 13 13 13 2
## 6 5 2 1039 2039 0 no 2 12 12 12 0 no 2 11 12 12 0
## 7 5 2 1131 2131 1 no 0 11 6 6 0 no 0 10 11 12 2
## 8 4 2 1069 2069 0 no 1 10 10 10 0 no 0 11 10 11 0
## 9 3 2 1070 2070 0 no 9 16 16 16 0 no 6 15 15 15 0
## 10 4 2 1106 2106 0 no 10 10 10 10 0 no 10 10 10 10 0
## paid.m absences.m G1.m G2.m G3.m alc_use high_use cid
## 1 yes 2 7 10 10 1.0 FALSE 3001
## 2 no 2 8 6 5 3.0 TRUE 3002
## 3 yes 8 14 13 13 1.0 FALSE 3003
## 4 yes 2 10 9 8 1.0 FALSE 3004
## 5 yes 8 10 10 10 2.5 TRUE 3005
## 6 yes 2 12 12 11 1.0 FALSE 3006
## 7 no 0 12 0 0 2.0 FALSE 3007
## 8 yes 2 8 9 8 2.0 FALSE 3008
## 9 no 12 16 16 16 2.5 TRUE 3009
## 10 no 10 10 11 11 1.0 FALSE 3010
Four interesting variables are selected from the analysis dataset, and the association of those variables with high/low alcohol use (high_use) is examined. The four selected variables are :
The hypothesis about the association of these variables with alcohol use is that the mean of absences is higher and health status is lower among those with high alcohol use. Furthermore, it is assumed that high alcohol use is more frequent among men than among women, and that age is positively associated with high alcohol use.
There are 111 high alcohol users and 259 low alcohol users in the data. The age range is 15 to 22 years, and there are 195 women and 175 men in the analysis dataset. The mean of absences varies from 0 to 45. When looking the graphical presentation of the pairwise associations between the variables, there seems to be more absences among the high alcohol users. Also, high alcohol users are older than low alcohol users, and the proportion of high alcohol use is higher among men than among women, However, there seems to be no association between high alcohol use and health status. Furthermore, looking the proportions of health status classes by alcohol use, there seems to be no difference.
These findings are in line with the prior hypothesis, except for health status, where a lower health was assumed to be associated with high alcohol use.
summary(subset(pormath, select=c('high_use','absences','health','sex','age')))
## high_use absences health sex age
## Mode :logical Min. : 0.000 Min. :1.000 Length:370 Min. :15.00
## FALSE:259 1st Qu.: 1.000 1st Qu.:3.000 Class :character 1st Qu.:16.00
## TRUE :111 Median : 3.000 Median :4.000 Mode :character Median :17.00
## Mean : 4.511 Mean :3.562 Mean :16.58
## 3rd Qu.: 6.000 3rd Qu.:5.000 3rd Qu.:17.00
## Max. :45.000 Max. :5.000 Max. :22.00
table(pormath$sex)
##
## F M
## 195 175
p <- ggpairs(subset(pormath, select=c('high_use','absences','health','sex','age')), mapping = aes(col=high_use,alpha=0.3), lower = list(combo = wrap("facethist", bins = 20)))
p
table(pormath$high_use,pormath$health) %>% prop.table(1)
##
## 1 2 3 4 5
## FALSE 0.1351351 0.1081081 0.2355212 0.1737452 0.3474903
## TRUE 0.0990991 0.1261261 0.1711712 0.1531532 0.4504505
Logistic regression model was fitted with high alcohol use as target variables and the four selected variables as explanatory variables.
The mean of absences an sex have statistically significant association with high alcohol use. The odds ratio of absences is 1.097 with the interpretation that the expected increase in the odds of being a high alcohol user in 9.7%, for a one-unit increase in absences. Likewise, the expected odds of being a high alcohol user is 2.72 higher for men than for women.
The results indicate that the prior hypothesis concerning absences and sex was correct. However, there is not enough evidence for the hypothesis that older age and lower health were positively associated wth high alcohol use.
m <- glm(high_use ~ absences + health + sex + age, data = pormath, family = "binomial")
summary(m)
##
## Call:
## glm(formula = high_use ~ absences + health + sex + age, family = "binomial",
## data = pormath)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -2.3556 -0.8424 -0.6086 1.0700 2.1619
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -4.87786 1.75660 -2.777 0.00549 **
## absences 0.09264 0.02344 3.952 7.75e-05 ***
## health 0.09525 0.08878 1.073 0.28332
## sexM 1.00325 0.24684 4.064 4.82e-05 ***
## age 0.16347 0.10202 1.602 0.10907
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 452.04 on 369 degrees of freedom
## Residual deviance: 412.11 on 365 degrees of freedom
## AIC: 422.11
##
## Number of Fisher Scoring iterations: 4
Coeff <- coef(m) %>% exp
CI <- confint(m) %>% exp
## Waiting for profiling to be done...
cbind(Coeff,CI)
## Coeff 2.5 % 97.5 %
## (Intercept) 0.007613307 0.0002295193 0.2288702
## absences 1.097072080 1.0500011255 1.1512256
## health 1.099938481 0.9259125849 1.3125241
## sexM 2.727130101 1.6910032352 4.4591635
## age 1.177595137 0.9652572862 1.4414744
The model with only absences and sex as explanatory variables is fitted and model performance is evaluated. 91% of the students are predicted as low alcohol users and 9% are predicted as high alcohol users. 68% of students are both low alcohol users and predicted as low alcohol users. The corresponding figure for high alcohol users is 7%. The training error is 25%. This performance is compared to simple guessing strategies: all students are predicted to be low alcohol users and high alcohol users. The performance of these strategies was worse than the training error.
m2 <- glm(high_use ~ absences + sex, data = pormath, family = "binomial")
probabilities <- predict(m2, type = "response")
pormath <- mutate(pormath, probability = probabilities)
pormath <- mutate(pormath, prediction = probability>0.5)
# tabulate the target variable versus the predictions
with(pormath,table(high_use, prediction))
## prediction
## high_use FALSE TRUE
## FALSE 251 8
## TRUE 86 25
# table with proportions
table(high_use = pormath$high_use, prediction = pormath$prediction) %>% prop.table %>% addmargins()
## prediction
## high_use FALSE TRUE Sum
## FALSE 0.67837838 0.02162162 0.70000000
## TRUE 0.23243243 0.06756757 0.30000000
## Sum 0.91081081 0.08918919 1.00000000
# plot
g <- ggplot(pormath, aes(x = probability, y = high_use, col=prediction)) + geom_point()
g
# define a loss function (mean prediction error)
loss_func <- function(class, prob) {
n_wrong <- abs(class - prob) > 0.5
mean(n_wrong)
}
#training error:
loss_func(class = pormath$high_use, prob = pormath$probability)
## [1] 0.2540541
#simple guessing strategies:
loss_func(class = pormath$high_use, prob = 0)
## [1] 0.3
loss_func(class = pormath$high_use, prob = 1)
## [1] 0.7
In this week analysis we use data consisting of housing values in suburbs of Boston from R package MASS. The data has information about socio-economic, business, geographical, and environmental characteristics of towns in Boston. The data has 506 rows and 14 columns with all the variables numeric, with the exception of dummy variable chas . The description of the data is here.
The distributions of crim, zn, dis, and black are very skewed, while the distributions of indus, rad and tax are bimodal. The largest correlations are between indus and nox (positive), indus and dis (negative), indus and tax (positive), nox and age (positive), nox and dis (negative), age and dis (negative), rad and tax (positive), and lstat and medv (negative).
data("Boston") #loading data
str(Boston) #structure
## 'data.frame': 506 obs. of 14 variables:
## $ crim : num 0.00632 0.02731 0.02729 0.03237 0.06905 ...
## $ zn : num 18 0 0 0 0 0 12.5 12.5 12.5 12.5 ...
## $ indus : num 2.31 7.07 7.07 2.18 2.18 2.18 7.87 7.87 7.87 7.87 ...
## $ chas : int 0 0 0 0 0 0 0 0 0 0 ...
## $ nox : num 0.538 0.469 0.469 0.458 0.458 0.458 0.524 0.524 0.524 0.524 ...
## $ rm : num 6.58 6.42 7.18 7 7.15 ...
## $ age : num 65.2 78.9 61.1 45.8 54.2 58.7 66.6 96.1 100 85.9 ...
## $ dis : num 4.09 4.97 4.97 6.06 6.06 ...
## $ rad : int 1 2 2 3 3 3 5 5 5 5 ...
## $ tax : num 296 242 242 222 222 222 311 311 311 311 ...
## $ ptratio: num 15.3 17.8 17.8 18.7 18.7 18.7 15.2 15.2 15.2 15.2 ...
## $ black : num 397 397 393 395 397 ...
## $ lstat : num 4.98 9.14 4.03 2.94 5.33 ...
## $ medv : num 24 21.6 34.7 33.4 36.2 28.7 22.9 27.1 16.5 18.9 ...
dim(Boston) #dimensions
## [1] 506 14
summary(Boston)
## crim zn indus chas nox rm
## Min. : 0.00632 Min. : 0.00 Min. : 0.46 Min. :0.00000 Min. :0.3850 Min. :3.561
## 1st Qu.: 0.08205 1st Qu.: 0.00 1st Qu.: 5.19 1st Qu.:0.00000 1st Qu.:0.4490 1st Qu.:5.886
## Median : 0.25651 Median : 0.00 Median : 9.69 Median :0.00000 Median :0.5380 Median :6.208
## Mean : 3.61352 Mean : 11.36 Mean :11.14 Mean :0.06917 Mean :0.5547 Mean :6.285
## 3rd Qu.: 3.67708 3rd Qu.: 12.50 3rd Qu.:18.10 3rd Qu.:0.00000 3rd Qu.:0.6240 3rd Qu.:6.623
## Max. :88.97620 Max. :100.00 Max. :27.74 Max. :1.00000 Max. :0.8710 Max. :8.780
## age dis rad tax ptratio black
## Min. : 2.90 Min. : 1.130 Min. : 1.000 Min. :187.0 Min. :12.60 Min. : 0.32
## 1st Qu.: 45.02 1st Qu.: 2.100 1st Qu.: 4.000 1st Qu.:279.0 1st Qu.:17.40 1st Qu.:375.38
## Median : 77.50 Median : 3.207 Median : 5.000 Median :330.0 Median :19.05 Median :391.44
## Mean : 68.57 Mean : 3.795 Mean : 9.549 Mean :408.2 Mean :18.46 Mean :356.67
## 3rd Qu.: 94.08 3rd Qu.: 5.188 3rd Qu.:24.000 3rd Qu.:666.0 3rd Qu.:20.20 3rd Qu.:396.23
## Max. :100.00 Max. :12.127 Max. :24.000 Max. :711.0 Max. :22.00 Max. :396.90
## lstat medv
## Min. : 1.73 Min. : 5.00
## 1st Qu.: 6.95 1st Qu.:17.02
## Median :11.36 Median :21.20
## Mean :12.65 Mean :22.53
## 3rd Qu.:16.95 3rd Qu.:25.00
## Max. :37.97 Max. :50.00
p <- ggpairs(Boston, mapping = aes(), lower = list(combo = wrap("facethist", bins = 20)))
p
The standardized data is summarized below. All the standardized variables have a mean equal to 0 and a standard deviation equal to 1. A new categorical variable crime is derived and data is divided into train and test sets.
boston_scaled <- data.frame(scale(Boston))
summary(boston_scaled)
## crim zn indus chas nox
## Min. :-0.419367 Min. :-0.48724 Min. :-1.5563 Min. :-0.2723 Min. :-1.4644
## 1st Qu.:-0.410563 1st Qu.:-0.48724 1st Qu.:-0.8668 1st Qu.:-0.2723 1st Qu.:-0.9121
## Median :-0.390280 Median :-0.48724 Median :-0.2109 Median :-0.2723 Median :-0.1441
## Mean : 0.000000 Mean : 0.00000 Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 0.007389 3rd Qu.: 0.04872 3rd Qu.: 1.0150 3rd Qu.:-0.2723 3rd Qu.: 0.5981
## Max. : 9.924110 Max. : 3.80047 Max. : 2.4202 Max. : 3.6648 Max. : 2.7296
## rm age dis rad tax ptratio
## Min. :-3.8764 Min. :-2.3331 Min. :-1.2658 Min. :-0.9819 Min. :-1.3127 Min. :-2.7047
## 1st Qu.:-0.5681 1st Qu.:-0.8366 1st Qu.:-0.8049 1st Qu.:-0.6373 1st Qu.:-0.7668 1st Qu.:-0.4876
## Median :-0.1084 Median : 0.3171 Median :-0.2790 Median :-0.5225 Median :-0.4642 Median : 0.2746
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000 Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 0.4823 3rd Qu.: 0.9059 3rd Qu.: 0.6617 3rd Qu.: 1.6596 3rd Qu.: 1.5294 3rd Qu.: 0.8058
## Max. : 3.5515 Max. : 1.1164 Max. : 3.9566 Max. : 1.6596 Max. : 1.7964 Max. : 1.6372
## black lstat medv
## Min. :-3.9033 Min. :-1.5296 Min. :-1.9063
## 1st Qu.: 0.2049 1st Qu.:-0.7986 1st Qu.:-0.5989
## Median : 0.3808 Median :-0.1811 Median :-0.1449
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 0.4332 3rd Qu.: 0.6024 3rd Qu.: 0.2683
## Max. : 0.4406 Max. : 3.5453 Max. : 2.9865
#New variable `crime` is derived:
bins <- quantile(boston_scaled$crim)
crime <- cut(boston_scaled$crim, breaks = bins, include.lowest = TRUE, label = c("low","med_low","med_high","high"))
boston_scaled$crim <- NULL
boston_scaled$crime <- crime
#Dividing the data to train and test datasets:
ind <- sample(nrow(boston_scaled), size = nrow(boston_scaled) * 0.8)
train <- boston_scaled[ind,] #training set
test <- boston_scaled[-ind,] #test set
Linear discriminant analysis is fitted on the training set with the variable crime as target variable. Then, biplot is drawn.
lda.fit <- lda(crime~., data = train)
# the function for lda biplot arrows
lda.arrows <- function(x, myscale = 1, arrow_heads = 0.1, color = "red", tex = 0.75, choices = c(1,2)){
heads <- coef(x)
arrows(x0 = 0, y0 = 0,
x1 = myscale * heads[,choices[1]],
y1 = myscale * heads[,choices[2]], col=color, length = arrow_heads)
text(myscale * heads[,choices], labels = row.names(heads),
cex = tex, col=color, pos=3)
}
# target classes as numeric
classes <- as.numeric(train$crime)
# plot the lda results
plot(lda.fit, dimen = 2, col=classes,pch=classes)
lda.arrows(lda.fit, myscale = 2)
The crime classes of the test set are predicted using the fitted LDA model. When tabulating the correct and the predicted values, there are nine observations with correct value “low” and predicted value “med_low”, and nine observations with correct value “med_low” and predicted value “med_high”. Otherwise the predicted values seem to correspond the correct values well.
correct_classes <- test$crime #saving crime categories
test$crime <- NULL #removing crime from test set
lda.pred <- predict(lda.fit, newdata = test)
table(correct = correct_classes, predicted = lda.pred$class)
## predicted
## correct low med_low med_high high
## low 10 14 2 0
## med_low 3 15 8 0
## med_high 1 8 12 2
## high 0 0 0 27
The distances between the observations in the scaled Boston data are calculated. K-means algorithm is run with number of clusters from 1 to 10 to find the optimal number of clusters. The resulting plot shows that the total of within cluster sum of squares drops most radically when the number of clusters is two. When looking at the visualization of the two clusters in relation of the variables in Boston data, we see that the distributions of indus, nox, dis, and tax by cluster separates the clusters quite well. The distribution of rm by cluster are almost identical.
data(Boston)
boston_scaled <- scale(Boston)
dist_eu <- dist(boston_scaled) #distances
set.seed(544356)
twcss <- sapply(1:10, function(k){kmeans(boston_scaled, k)$tot.withinss}) #total within cluster sum of squares
# visualize the results
qplot(x = 1:10, y = twcss, geom = 'line') + scale_x_continuous(breaks=seq(1,10,by=1)) + xlab('number of clusters')
km <-kmeans(boston_scaled, centers = 2) #km-algorithm with the number of clusters = 2
p <- ggpairs(data.frame(boston_scaled), mapping = aes(col = factor(km$cluster), alpha=0.3), lower = list(combo = wrap("facethist", bins = 20)))
p
The distributions of GNI_cap, mm_ratio, and a_birth_arte are very skewed, while the distributions of labF, exp_edu and parlrep_p seem to follow normal distribution. The highest correlation is between mm_ratio and life_exp (-0.857), and there are also several other high correlations between exp_edu, edu2F, life_exp, mm_ratio and a_birth_rate.
human <- read.csv(file="/home/jkox/Git/proj/IODS-project/data/human.csv",row.names = 1)
str(human) #structure
## 'data.frame': 155 obs. of 8 variables:
## $ edu2F : num 97.4 94.3 95 95.5 87.7 96.3 80.5 95.1 100 95 ...
## $ labF : num 61.2 58.8 61.8 58.7 58.5 53.6 53.1 56.3 61.6 62 ...
## $ exp_edu : num 17.5 20.2 15.8 18.7 17.9 16.5 18.6 16.5 15.9 19.2 ...
## $ life_exp : num 81.6 82.4 83 80.2 81.6 80.9 80.9 79.1 82 81.8 ...
## $ GNI_cap : int 64992 42261 56431 44025 45435 43919 39568 52947 42155 32689 ...
## $ mm_ratio : int 4 6 6 5 6 7 9 28 11 8 ...
## $ a_birth_rate: num 7.8 12.1 1.9 5.1 6.2 3.8 8.2 31 14.5 25.3 ...
## $ parlrep_p : num 39.6 30.5 28.5 38 36.9 36.9 19.9 19.4 28.2 31.4 ...
dim(human) #dimensions
## [1] 155 8
summary(human)
## edu2F labF exp_edu life_exp GNI_cap mm_ratio
## Min. : 0.90 Min. :13.50 Min. : 5.40 Min. :49.00 Min. : 581 Min. : 1.0
## 1st Qu.: 27.15 1st Qu.:44.45 1st Qu.:11.25 1st Qu.:66.30 1st Qu.: 4198 1st Qu.: 11.5
## Median : 56.60 Median :53.50 Median :13.50 Median :74.20 Median : 12040 Median : 49.0
## Mean : 55.37 Mean :52.52 Mean :13.18 Mean :71.65 Mean : 17628 Mean : 149.1
## 3rd Qu.: 85.15 3rd Qu.:61.90 3rd Qu.:15.20 3rd Qu.:77.25 3rd Qu.: 24512 3rd Qu.: 190.0
## Max. :100.00 Max. :88.10 Max. :20.20 Max. :83.50 Max. :123124 Max. :1100.0
## a_birth_rate parlrep_p
## Min. : 0.60 Min. : 0.00
## 1st Qu.: 12.65 1st Qu.:12.40
## Median : 33.60 Median :19.30
## Mean : 47.16 Mean :20.91
## 3rd Qu.: 71.95 3rd Qu.:27.95
## Max. :204.80 Max. :57.50
p <- ggpairs(human, mapping = aes(), lower = list(combo = wrap("facethist", bins = 20)))
p
First, PCA is performed with not standardized data. The first principal component captures all the variablity of the data. Looking at the biplot we see, that GNI_cap is the only variable influencing PC1, since only the arrow of GNI_cap is parallel to the x-axis. Nothing can be said about the correlations between variables, since the direction of the arrows of other variables is not visible.
pca_human <- prcomp(human)
summary(pca_human)
## Importance of components:
## PC1 PC2 PC3 PC4 PC5 PC6 PC7 PC8
## Standard deviation 1.854e+04 186.2835 25.97 20.07 14.32 10.63 3.721 1.428
## Proportion of Variance 9.999e-01 0.0001 0.00 0.00 0.00 0.00 0.000 0.000
## Cumulative Proportion 9.999e-01 1.0000 1.00 1.00 1.00 1.00 1.000 1.000
round(100*summary(pca_human)$importance[2, ], digits = 1) # rounded percetanges of variance captured by each PC
## PC1 PC2 PC3 PC4 PC5 PC6 PC7 PC8
## 100 0 0 0 0 0 0 0
biplot(pca_human, choices = 1:2, cex=c(0.8,1), col=c("grey40","deeppink2"))
Then, PCA is performed again with standardized data. Now, the first principal compenent captures 57% and the second principal component 16% of the variability. These percentages are included as captions in the biplot. Variables exp_edu, edu2F, life_exp, mm_ratio, a_birth_rate, and GNI_cap are influencing PC1 approximately equally (looking at the length of the arrows), since their arrows are parallel to the x-axis. Looking at the direction of the arrows, variables exp_edu, edu2F, life_exp, and GNI_cap have strong positive correlation between them, as have mm_ratio and a_birth_rate. However, mm_ratio and a_birth_rate have strong negative correlation with exp_edu, edu2F, life_exp, and GNI_cap. Variables parlrep_p and labF are influencing PC2 equally. They also have a positive correlation between them.
human_std <- scale(human)
pca_human_std <- prcomp(human_std)
s_std <- summary(pca_human_std)
pca_pr <- round(100*s_std$importance[2, ], digits = 1)
pca_pr # rounded percetanges of variance captured by each PC
## PC1 PC2 PC3 PC4 PC5 PC6 PC7 PC8
## 57.0 15.6 9.6 6.5 3.8 3.5 2.5 1.4
pc_lab <- paste0(c('Human development','Equality'), " (", pca_pr, "%)") # create object pc_lab to be used as axis labels
biplot(pca_human_std, choices = 1:2, cex=c(0.8,1), col=c("grey40","deeppink2"), xlab = pc_lab[1], ylab = pc_lab[2])
The results between two PCAs are different. This is mostly due to the fact that the not standardized values of GNI_cap are much larger compared to other variables, and therefore GNI_cap dominates the PCA with not standardized data, and the effect of other variables remains hidden.
The first principal component consists of variables relating to education, mortality, and wealth, which all describe the development of a country. So, the first principal component is named ‘Human development’ (also in the biplot). The second principal component is named ‘Equality’, since variables parlrep_p and labF are percentages of female participation in parliament and labour force, respectively.
The tea dataset is used for MCA. The structure, the dimensions, and the visualization of the data are presented below.
library(FactoMineR)
library(tidyr)
data(tea)
str(tea)
## 'data.frame': 300 obs. of 36 variables:
## $ breakfast : Factor w/ 2 levels "breakfast","Not.breakfast": 1 1 2 2 1 2 1 2 1 1 ...
## $ tea.time : Factor w/ 2 levels "Not.tea time",..: 1 1 2 1 1 1 2 2 2 1 ...
## $ evening : Factor w/ 2 levels "evening","Not.evening": 2 2 1 2 1 2 2 1 2 1 ...
## $ lunch : Factor w/ 2 levels "lunch","Not.lunch": 2 2 2 2 2 2 2 2 2 2 ...
## $ dinner : Factor w/ 2 levels "dinner","Not.dinner": 2 2 1 1 2 1 2 2 2 2 ...
## $ always : Factor w/ 2 levels "always","Not.always": 2 2 2 2 1 2 2 2 2 2 ...
## $ home : Factor w/ 2 levels "home","Not.home": 1 1 1 1 1 1 1 1 1 1 ...
## $ work : Factor w/ 2 levels "Not.work","work": 1 1 2 1 1 1 1 1 1 1 ...
## $ tearoom : Factor w/ 2 levels "Not.tearoom",..: 1 1 1 1 1 1 1 1 1 2 ...
## $ friends : Factor w/ 2 levels "friends","Not.friends": 2 2 1 2 2 2 1 2 2 2 ...
## $ resto : Factor w/ 2 levels "Not.resto","resto": 1 1 2 1 1 1 1 1 1 1 ...
## $ pub : Factor w/ 2 levels "Not.pub","pub": 1 1 1 1 1 1 1 1 1 1 ...
## $ Tea : Factor w/ 3 levels "black","Earl Grey",..: 1 1 2 2 2 2 2 1 2 1 ...
## $ How : Factor w/ 4 levels "alone","lemon",..: 1 3 1 1 1 1 1 3 3 1 ...
## $ sugar : Factor w/ 2 levels "No.sugar","sugar": 2 1 1 2 1 1 1 1 1 1 ...
## $ how : Factor w/ 3 levels "tea bag","tea bag+unpackaged",..: 1 1 1 1 1 1 1 1 2 2 ...
## $ where : Factor w/ 3 levels "chain store",..: 1 1 1 1 1 1 1 1 2 2 ...
## $ price : Factor w/ 6 levels "p_branded","p_cheap",..: 4 6 6 6 6 3 6 6 5 5 ...
## $ age : int 39 45 47 23 48 21 37 36 40 37 ...
## $ sex : Factor w/ 2 levels "F","M": 2 1 1 2 2 2 2 1 2 2 ...
## $ SPC : Factor w/ 7 levels "employee","middle",..: 2 2 4 6 1 6 5 2 5 5 ...
## $ Sport : Factor w/ 2 levels "Not.sportsman",..: 2 2 2 1 2 2 2 2 2 1 ...
## $ age_Q : Factor w/ 5 levels "15-24","25-34",..: 3 4 4 1 4 1 3 3 3 3 ...
## $ frequency : Factor w/ 4 levels "1/day","1 to 2/week",..: 1 1 3 1 3 1 4 2 3 3 ...
## $ escape.exoticism: Factor w/ 2 levels "escape-exoticism",..: 2 1 2 1 1 2 2 2 2 2 ...
## $ spirituality : Factor w/ 2 levels "Not.spirituality",..: 1 1 1 2 2 1 1 1 1 1 ...
## $ healthy : Factor w/ 2 levels "healthy","Not.healthy": 1 1 1 1 2 1 1 1 2 1 ...
## $ diuretic : Factor w/ 2 levels "diuretic","Not.diuretic": 2 1 1 2 1 2 2 2 2 1 ...
## $ friendliness : Factor w/ 2 levels "friendliness",..: 2 2 1 2 1 2 2 1 2 1 ...
## $ iron.absorption : Factor w/ 2 levels "iron absorption",..: 2 2 2 2 2 2 2 2 2 2 ...
## $ feminine : Factor w/ 2 levels "feminine","Not.feminine": 2 2 2 2 2 2 2 1 2 2 ...
## $ sophisticated : Factor w/ 2 levels "Not.sophisticated",..: 1 1 1 2 1 1 1 2 2 1 ...
## $ slimming : Factor w/ 2 levels "No.slimming",..: 1 1 1 1 1 1 1 1 1 1 ...
## $ exciting : Factor w/ 2 levels "exciting","No.exciting": 2 1 2 2 2 2 2 2 2 2 ...
## $ relaxing : Factor w/ 2 levels "No.relaxing",..: 1 1 2 2 2 2 2 2 2 2 ...
## $ effect.on.health: Factor w/ 2 levels "effect on health",..: 2 2 2 2 2 2 2 2 2 2 ...
dim(tea)
## [1] 300 36
gather(tea) %>% ggplot(aes(value)) + facet_wrap("key", scales = "free") + geom_bar() + theme(axis.text.x = element_text(angle = 45, hjust = 1, size = 8))
MCA is performed for all the categorical variables in the tea dataset. This leaves out continuous variable age. The first dimension captures 5.8% of the variation, and the second dimension 5.3%. The small percentages are most probably due to all variables being selected to the analysis. When looking at the biplot, we see that categories ‘other’, ‘tearoom’, ‘chain store+tea shop’, and ‘dinner’ are the most influential categories for dimension 1. Similarly, categories ‘tea shop’, ‘+60’, ‘unpackaged’, ‘p_upscale’, ‘student’, and ‘15-24’ are the most influential categories for dimension 2. If the categories are on opposite sides of the plot, a dimension contrasts these categories. For instance, categories ‘+60’ and ‘15-24’ are on the opposite sides of the plot in relation of dimension 2.
mca <- MCA(tea[,-19], graph = FALSE) #age is excluded
summary(mca)
##
## Call:
## MCA(X = tea[, -19], graph = FALSE)
##
##
## Eigenvalues
## Dim.1 Dim.2 Dim.3 Dim.4 Dim.5 Dim.6 Dim.7 Dim.8 Dim.9 Dim.10 Dim.11
## Variance 0.090 0.082 0.070 0.063 0.056 0.053 0.050 0.048 0.047 0.044 0.041
## % of var. 5.838 5.292 4.551 4.057 3.616 3.465 3.272 3.090 3.053 2.834 2.643
## Cumulative % of var. 5.838 11.130 15.681 19.738 23.354 26.819 30.091 33.181 36.234 39.068 41.711
## Dim.12 Dim.13 Dim.14 Dim.15 Dim.16 Dim.17 Dim.18 Dim.19 Dim.20 Dim.21 Dim.22
## Variance 0.040 0.039 0.037 0.036 0.035 0.034 0.032 0.031 0.031 0.030 0.028
## % of var. 2.623 2.531 2.388 2.302 2.275 2.172 2.085 2.013 2.011 1.915 1.847
## Cumulative % of var. 44.334 46.865 49.252 51.554 53.829 56.000 58.086 60.099 62.110 64.025 65.872
## Dim.23 Dim.24 Dim.25 Dim.26 Dim.27 Dim.28 Dim.29 Dim.30 Dim.31 Dim.32 Dim.33
## Variance 0.027 0.026 0.025 0.025 0.024 0.024 0.023 0.022 0.021 0.020 0.020
## % of var. 1.740 1.686 1.638 1.609 1.571 1.524 1.459 1.425 1.378 1.322 1.281
## Cumulative % of var. 67.611 69.297 70.935 72.544 74.115 75.639 77.099 78.523 79.901 81.223 82.504
## Dim.34 Dim.35 Dim.36 Dim.37 Dim.38 Dim.39 Dim.40 Dim.41 Dim.42 Dim.43 Dim.44
## Variance 0.019 0.019 0.018 0.017 0.017 0.016 0.015 0.015 0.014 0.014 0.013
## % of var. 1.241 1.222 1.152 1.092 1.072 1.019 0.993 0.950 0.924 0.891 0.833
## Cumulative % of var. 83.745 84.967 86.119 87.211 88.283 89.301 90.294 91.244 92.169 93.060 93.893
## Dim.45 Dim.46 Dim.47 Dim.48 Dim.49 Dim.50 Dim.51 Dim.52 Dim.53 Dim.54
## Variance 0.012 0.011 0.011 0.010 0.010 0.009 0.009 0.008 0.007 0.006
## % of var. 0.792 0.729 0.716 0.666 0.660 0.605 0.584 0.519 0.447 0.390
## Cumulative % of var. 94.684 95.414 96.130 96.796 97.456 98.060 98.644 99.163 99.610 100.000
##
## Individuals (the 10 first)
## Dim.1 ctr cos2 Dim.2 ctr cos2 Dim.3 ctr cos2
## 1 | -0.580 1.246 0.174 | 0.155 0.098 0.012 | 0.052 0.013 0.001 |
## 2 | -0.376 0.522 0.108 | 0.293 0.350 0.066 | -0.164 0.127 0.021 |
## 3 | 0.083 0.026 0.004 | -0.155 0.099 0.015 | 0.122 0.071 0.009 |
## 4 | -0.569 1.196 0.236 | -0.273 0.304 0.054 | -0.019 0.002 0.000 |
## 5 | -0.145 0.078 0.020 | -0.142 0.083 0.019 | 0.002 0.000 0.000 |
## 6 | -0.676 1.693 0.272 | -0.284 0.330 0.048 | -0.021 0.002 0.000 |
## 7 | -0.191 0.135 0.027 | 0.020 0.002 0.000 | 0.141 0.095 0.015 |
## 8 | -0.043 0.007 0.001 | 0.108 0.047 0.009 | -0.089 0.038 0.006 |
## 9 | -0.027 0.003 0.000 | 0.267 0.291 0.049 | 0.341 0.553 0.080 |
## 10 | 0.205 0.155 0.028 | 0.366 0.546 0.089 | 0.281 0.374 0.052 |
##
## Categories (the 10 first)
## Dim.1 ctr cos2 v.test Dim.2 ctr cos2 v.test Dim.3 ctr cos2 v.test
## breakfast | 0.182 0.504 0.031 3.022 | 0.020 0.007 0.000 0.330 | -0.107 0.225 0.011 -1.784 |
## Not.breakfast | -0.168 0.465 0.031 -3.022 | -0.018 0.006 0.000 -0.330 | 0.099 0.208 0.011 1.784 |
## Not.tea time | -0.556 4.286 0.240 -8.468 | 0.004 0.000 0.000 0.065 | 0.062 0.069 0.003 0.950 |
## tea time | 0.431 3.322 0.240 8.468 | -0.003 0.000 0.000 -0.065 | -0.048 0.054 0.003 -0.950 |
## evening | 0.276 0.830 0.040 3.452 | -0.409 2.006 0.087 -5.109 | 0.344 1.653 0.062 4.301 |
## Not.evening | -0.144 0.434 0.040 -3.452 | 0.214 1.049 0.087 5.109 | -0.180 0.864 0.062 -4.301 |
## lunch | 0.601 1.678 0.062 4.306 | -0.408 0.854 0.029 -2.924 | 0.240 0.343 0.010 1.719 |
## Not.lunch | -0.103 0.288 0.062 -4.306 | 0.070 0.147 0.029 2.924 | -0.041 0.059 0.010 -1.719 |
## dinner | -1.105 2.709 0.092 -5.240 | -0.081 0.016 0.000 -0.386 | 0.796 1.805 0.048 3.777 |
## Not.dinner | 0.083 0.204 0.092 5.240 | 0.006 0.001 0.000 0.386 | -0.060 0.136 0.048 -3.777 |
##
## Categorical variables (eta2)
## Dim.1 Dim.2 Dim.3
## breakfast | 0.031 0.000 0.011 |
## tea.time | 0.240 0.000 0.003 |
## evening | 0.040 0.087 0.062 |
## lunch | 0.062 0.029 0.010 |
## dinner | 0.092 0.000 0.048 |
## always | 0.056 0.035 0.007 |
## home | 0.016 0.002 0.030 |
## work | 0.075 0.020 0.022 |
## tearoom | 0.321 0.019 0.031 |
## friends | 0.186 0.061 0.030 |
plot(mca, invisible=c("ind"), habillage = "quali", grapth.type = "classic")
RATS data (in long format) is used for implementing the analyses of Chapter 8 of MABS.
RATS <- read.table("https://raw.githubusercontent.com/KimmoVehkalahti/MABS/master/Examples/data/rats.txt", header = TRUE) #reading RATS data in wide format
RATSL <- read.csv(file="/home/jkox/Git/proj/IODS-project/data/RATSL.csv") #reading RATS data is long format
#convertng as factors:
RATSL$ID <- factor(RATSL$ID)
RATSL$Group <- factor(RATSL$Group)
glimpse(RATSL) #glimpsing data
## Rows: 176
## Columns: 5
## $ ID <fct> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,…
## $ Group <fct> 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, …
## $ WD <chr> "WD1", "WD1", "WD1", "WD1", "WD1", "WD1", "WD1", "WD1", "WD1", "WD1", "WD1", "WD1", "WD1", "W…
## $ Weight <int> 240, 225, 245, 260, 255, 260, 275, 245, 410, 405, 445, 555, 470, 535, 520, 510, 250, 230, 250…
## $ Time <int> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, …
First, the plot with individual response profiles is drawn. We see that weights in group 1 are lower than in groups 2 and 3, and weights in group 2 seem to be lower than in group 3. In all groups, there is one individual with weights on a different level compared to other individuals in the same group (outlier). In all groups, weights seem to increase over time.
After standardizing weight measurements, we see that the difference between groups 2 and 3 becomes clearer. Also, the increasing trends in weights disappear.
# Draw the plot
ggplot(RATSL, aes(x = Time, y = Weight, linetype = ID)) +
geom_line() +
scale_linetype_manual(values = rep(1:10, times=4)) +
facet_grid(. ~ Group, labeller = label_both) +
theme(legend.position = "none") +
scale_y_continuous(limits = c(min(RATSL$Weight), max(RATSL$Weight)))
# Standardise the variable Weight
RATSL <- RATSL %>%
group_by(Time) %>%
mutate(stdweight = (Weight-mean(Weight))/sd(Weight)) %>%
ungroup()
# Plot again with the standardised Weight
ggplot(RATSL, aes(x = Time, y = stdweight, linetype = ID)) +
geom_line() +
scale_linetype_manual(values = rep(1:10, times=4)) +
facet_grid(. ~ Group, labeller = label_both) +
theme(legend.position = "none") +
scale_y_continuous(name = "standardized Weight")
Then, we calculate the means and standard errors by group and time, and visualize them. Again, group 1 weights are lower than the weights of other two groups. However, there seems to be no difference between groups 2 and 3, since the error bars overlap. However, when drawing boxplots we see that in both groups 2 and 3 there is one outlier. These outliers might cause the overlapping error bars.
# Summary data with mean and standard error of Weight by Group and Time
RATSS <- RATSL %>%
group_by(Group, Time) %>%
summarise( mean = mean(Weight), se = sd(Weight)/sqrt(length(Weight)) ) %>%
ungroup()
# Plot the mean profiles
ggplot(RATSS, aes(x = Time, y = mean, linetype = Group, shape = Group)) +
geom_line() +
scale_linetype_manual(values = c(1,2,3)) +
geom_point(size=3) +
scale_shape_manual(values = c(1,2,3)) +
geom_errorbar(aes(ymin=mean-se, ymax=mean+se, linetype="1"), width=0.3) +
theme(legend.position = c(0.9,0.5)) +
scale_y_continuous(name = "mean(Weight) +/- se(Weight)")
# Boxplot by Time and Group
ggplot(RATSL, aes(x = factor(Time), y = Weight, fill=Group)) +
geom_boxplot() +
scale_x_discrete(name = "Time")
Next, boxplots by group are drawn with excluding the weight measurements of the first timepoint. We again see that there is one outlier in each group. The boxplots are drawn again without outliers.
# Create a summary data by Group and ID with mean as the summary variable (ignoring baseline Time 1).
RATSL8S <- RATSL %>%
filter(Time > 1) %>%
group_by(Group, ID) %>%
summarise( mean=mean(Weight) ) %>%
ungroup()
# Draw a boxplot of the mean versus treatment
ggplot(RATSL8S, aes(x = Group, y = mean)) +
geom_boxplot() +
stat_summary(fun = "mean", geom = "point", shape=23, size=4, fill = "white") +
scale_y_continuous(name = "mean(Weight), Time 1 excluded")
RATSL8S1 <- RATSL8S %>% filter(!((Group%in%1 & mean<240) | (Group%in%2 & mean>500) | (Group%in%3 & mean<500)))
ggplot(RATSL8S1, aes(x = Group, y = mean)) +
geom_boxplot() +
stat_summary(fun = "mean", geom = "point", shape=23, size=4, fill = "white") +
scale_y_continuous(name = "mean(Weight), Time 1 excluded")
Then, t-tests for testing the difference between the means of the groups are executed. With the data including outliers there is statistically significant difference between groups 1 and 2, and groups 1 and 3. However, when performing t-tests for data without outliers, all pairwise differences between groups are statistically significant.
t.test(mean ~ Group, data = RATSL8S, subset = Group%in%c(1,2), var.equal = TRUE) #p<<<0.05
##
## Two Sample t-test
##
## data: mean by Group
## t = -9.0646, df = 10, p-value = 3.88e-06
## alternative hypothesis: true difference in means between group 1 and group 2 is not equal to 0
## 95 percent confidence interval:
## -277.5345 -168.0155
## sample estimates:
## mean in group 1 mean in group 2
## 265.025 487.800
t.test(mean ~ Group, data = RATSL8S, subset = Group%in%c(1,3), var.equal = TRUE) #p<<<0.05
##
## Two Sample t-test
##
## data: mean by Group
## t = -27.824, df = 10, p-value = 8.345e-11
## alternative hypothesis: true difference in means between group 1 and group 3 is not equal to 0
## 95 percent confidence interval:
## -283.4943 -241.4557
## sample estimates:
## mean in group 1 mean in group 3
## 265.025 527.500
t.test(mean ~ Group, data = RATSL8S, subset = Group%in%c(2,3), var.equal = TRUE) #p=0.33
##
## Two Sample t-test
##
## data: mean by Group
## t = -1.0686, df = 6, p-value = 0.3263
## alternative hypothesis: true difference in means between group 2 and group 3 is not equal to 0
## 95 percent confidence interval:
## -130.60428 51.20428
## sample estimates:
## mean in group 2 mean in group 3
## 487.8 527.5
t.test(mean ~ Group, data = RATSL8S1, subset = Group%in%c(1,2), var.equal = TRUE) #p<<<0.05
##
## Two Sample t-test
##
## data: mean by Group
## t = -44.305, df = 8, p-value = 7.434e-11
## alternative hypothesis: true difference in means between group 1 and group 2 is not equal to 0
## 95 percent confidence interval:
## -193.2012 -174.0845
## sample estimates:
## mean in group 1 mean in group 2
## 268.7571 452.4000
t.test(mean ~ Group, data = RATSL8S1, subset = Group%in%c(1,3), var.equal = TRUE) #p<<<0.05
##
## Two Sample t-test
##
## data: mean by Group
## t = -77.715, df = 8, p-value = 8.377e-13
## alternative hypothesis: true difference in means between group 1 and group 3 is not equal to 0
## 95 percent confidence interval:
## -277.5065 -261.5125
## sample estimates:
## mean in group 1 mean in group 3
## 268.7571 538.2667
t.test(mean ~ Group, data = RATSL8S1, subset = Group%in%c(2,3), var.equal = TRUE) #p<<<0.05
##
## Two Sample t-test
##
## data: mean by Group
## t = -18.235, df = 4, p-value = 5.32e-05
## alternative hypothesis: true difference in means between group 2 and group 3 is not equal to 0
## 95 percent confidence interval:
## -98.94088 -72.79246
## sample estimates:
## mean in group 2 mean in group 3
## 452.4000 538.2667
Finally, we include the weight measurements of the first timepoint (baseline) in the analysis, and fit a linear model with mean as a response variable, and group and the baseline weight as explanatory variables. Results from analysis of variance show that baseline is statistically significant, and group is not. This implies that the baseline measurement is strongly associated with weight measurements after baseline, but there is no separate group effect after conditioning for the baseline value.
# Add the baseline from the original data as a new variable to the summary data
RATSL8S2 <- RATSL8S %>%
mutate(baseline = RATS$WD1)
# Fit the linear model with the mean as the response
fit <- lm(mean ~ baseline + Group, data = RATSL8S2)
# Compute the analysis of variance table for the fitted model with anova()
anova(fit)
## Analysis of Variance Table
##
## Response: mean
## Df Sum Sq Mean Sq F value Pr(>F)
## baseline 1 253625 253625 1859.8201 1.57e-14 ***
## Group 2 879 439 3.2219 0.07586 .
## Residuals 12 1636 136
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
BPRS data (in long format) is used for implementing the analyses of Chapter 9 of MABS.
BPRSL <- read.csv(file="/home/jkox/Git/proj/IODS-project/data/BPRSL.csv") #reading BPRS data is long format
# Factor variables subject and treatment
BPRSL$subject <- factor(BPRSL$subject)
BPRSL$treatment <- factor(BPRSL$treatment)
# Glimpse the data
glimpse(BPRSL)
## Rows: 360
## Columns: 5
## $ treatment <fct> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, …
## $ subject <fct> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 1, 2, 3, 4, 5, 6, 7…
## $ weeks <chr> "week0", "week0", "week0", "week0", "week0", "week0", "week0", "week0", "week0", "week0", …
## $ bprs <int> 42, 58, 54, 55, 72, 48, 71, 30, 41, 57, 30, 55, 36, 38, 66, 41, 45, 39, 24, 38, 52, 30, 65…
## $ week <int> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, …
First, linear model is fitted with ‘bprs’ as a response variable and ‘week’ and ‘treatment’ as explanatory variables. The model results show that ‘treatment’ is not statistically significant, but ‘week’ is.
Next, linear mixed model with random intercept is fitted. The interpretation is that own regression line with different intercepts is estimated for each individual. ANOVA test shows that this model provides a better fit than linear model.
Then, linear mixed model with random intercept and slope is fitted. Now for each individual a slope is also estimated. This model has a better fit than the random intercept model, according ANOVA test.
Finally, an interaction between ‘week’ and ‘treatment’ is added to the model. ANOVA test gives a p-value 0.07495, so this model has not a better fit than the random intercept and slope model without interaction.
# create a regression model RATS_reg
BPRS_reg <- lm(bprs ~ week + treatment, data=BPRSL)
# print out a summary of the model
summary(BPRS_reg)
##
## Call:
## lm(formula = bprs ~ week + treatment, data = BPRSL)
##
## Residuals:
## Min 1Q Median 3Q Max
## -22.454 -8.965 -3.196 7.002 50.244
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 46.4539 1.3670 33.982 <2e-16 ***
## week -2.2704 0.2524 -8.995 <2e-16 ***
## treatment2 0.5722 1.3034 0.439 0.661
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 12.37 on 357 degrees of freedom
## Multiple R-squared: 0.1851, Adjusted R-squared: 0.1806
## F-statistic: 40.55 on 2 and 357 DF, p-value: < 2.2e-16
# Create a random intercept model
BPRS_ref <- lmer(bprs ~ week + treatment + (1 | subject), data = BPRSL, REML = FALSE)
# Print the summary of the model
summary(BPRS_ref)
## Linear mixed model fit by maximum likelihood ['lmerMod']
## Formula: bprs ~ week + treatment + (1 | subject)
## Data: BPRSL
##
## AIC BIC logLik deviance df.resid
## 2748.7 2768.1 -1369.4 2738.7 355
##
## Scaled residuals:
## Min 1Q Median 3Q Max
## -3.0481 -0.6749 -0.1361 0.4813 3.4855
##
## Random effects:
## Groups Name Variance Std.Dev.
## subject (Intercept) 47.41 6.885
## Residual 104.21 10.208
## Number of obs: 360, groups: subject, 20
##
## Fixed effects:
## Estimate Std. Error t value
## (Intercept) 46.4539 1.9090 24.334
## week -2.2704 0.2084 -10.896
## treatment2 0.5722 1.0761 0.532
##
## Correlation of Fixed Effects:
## (Intr) week
## week -0.437
## treatment2 -0.282 0.000
# perform an ANOVA test on the two models
anova(BPRS_ref, BPRS_reg)
## Data: BPRSL
## Models:
## BPRS_reg: bprs ~ week + treatment
## BPRS_ref: bprs ~ week + treatment + (1 | subject)
## npar AIC BIC logLik deviance Chisq Df Pr(>Chisq)
## BPRS_reg 4 2837.3 2852.9 -1414.7 2829.3
## BPRS_ref 5 2748.7 2768.1 -1369.4 2738.7 90.624 1 < 2.2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
# create a random intercept and random slope model
BPRS_ref1 <- lmer(bprs ~ week + treatment + (week | subject), data = BPRSL, REML = FALSE)
# print a summary of the model
summary(BPRS_ref1)
## Linear mixed model fit by maximum likelihood ['lmerMod']
## Formula: bprs ~ week + treatment + (week | subject)
## Data: BPRSL
##
## AIC BIC logLik deviance df.resid
## 2745.4 2772.6 -1365.7 2731.4 353
##
## Scaled residuals:
## Min 1Q Median 3Q Max
## -2.8919 -0.6194 -0.0691 0.5531 3.7976
##
## Random effects:
## Groups Name Variance Std.Dev. Corr
## subject (Intercept) 64.8222 8.0512
## week 0.9609 0.9802 -0.51
## Residual 97.4305 9.8707
## Number of obs: 360, groups: subject, 20
##
## Fixed effects:
## Estimate Std. Error t value
## (Intercept) 46.4539 2.1052 22.066
## week -2.2704 0.2977 -7.626
## treatment2 0.5722 1.0405 0.550
##
## Correlation of Fixed Effects:
## (Intr) week
## week -0.582
## treatment2 -0.247 0.000
# perform an ANOVA test on the two models
anova(BPRS_ref1, BPRS_ref)
## Data: BPRSL
## Models:
## BPRS_ref: bprs ~ week + treatment + (1 | subject)
## BPRS_ref1: bprs ~ week + treatment + (week | subject)
## npar AIC BIC logLik deviance Chisq Df Pr(>Chisq)
## BPRS_ref 5 2748.7 2768.1 -1369.4 2738.7
## BPRS_ref1 7 2745.4 2772.6 -1365.7 2731.4 7.2721 2 0.02636 *
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
# create a random intercept and random slope model with the interaction
BPRS_ref2 <- lmer(bprs ~ week + treatment + week * treatment + (week | subject), data = BPRSL, REML = FALSE)
# print a summary of the model
summary(BPRS_ref2)
## Linear mixed model fit by maximum likelihood ['lmerMod']
## Formula: bprs ~ week + treatment + week * treatment + (week | subject)
## Data: BPRSL
##
## AIC BIC logLik deviance df.resid
## 2744.3 2775.4 -1364.1 2728.3 352
##
## Scaled residuals:
## Min 1Q Median 3Q Max
## -3.0512 -0.6271 -0.0768 0.5288 3.9260
##
## Random effects:
## Groups Name Variance Std.Dev. Corr
## subject (Intercept) 64.9964 8.0620
## week 0.9687 0.9842 -0.51
## Residual 96.4707 9.8220
## Number of obs: 360, groups: subject, 20
##
## Fixed effects:
## Estimate Std. Error t value
## (Intercept) 47.8856 2.2521 21.262
## week -2.6283 0.3589 -7.323
## treatment2 -2.2911 1.9090 -1.200
## week:treatment2 0.7158 0.4010 1.785
##
## Correlation of Fixed Effects:
## (Intr) week trtmn2
## week -0.650
## treatment2 -0.424 0.469
## wek:trtmnt2 0.356 -0.559 -0.840
# perform an ANOVA test on the two models
anova(BPRS_ref2, BPRS_ref1)
## Data: BPRSL
## Models:
## BPRS_ref1: bprs ~ week + treatment + (week | subject)
## BPRS_ref2: bprs ~ week + treatment + week * treatment + (week | subject)
## npar AIC BIC logLik deviance Chisq Df Pr(>Chisq)
## BPRS_ref1 7 2745.4 2772.6 -1365.7 2731.4
## BPRS_ref2 8 2744.3 2775.4 -1364.1 2728.3 3.1712 1 0.07495 .
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
When plotting the original ‘bprs’ values and fitted values from the the random intercept and slope model with interaction by ‘week’ and ‘treatment’, we see that the ‘bprs’ values for each individual are estimated with separate intercept and slope.
# Plot the BPRSL data
ggplot(BPRSL, aes(x = week, y = bprs, linetype = subject)) +
geom_line() +
scale_linetype_manual(values = rep(1:10, times=4)) +
facet_grid(. ~ treatment, labeller = label_both) +
theme(legend.position = "none") +
scale_y_continuous(limits = c(min(BPRSL$bprs), max(BPRSL$bprs)))
# Create a vector of the fitted values
Fitted <- fitted(BPRS_ref2)
# Create a new column fitted to RATSL
BPRSL <- BPRSL %>% mutate(fitted = Fitted)
# draw the plot with the fitted values
ggplot(BPRSL, aes(x = week, y = Fitted, linetype = subject)) +
geom_line() +
scale_linetype_manual(values = rep(1:10, times=4)) +
facet_grid(. ~ treatment, labeller = label_both) +
theme(legend.position = "none")
(more chapters to be added similarly as we proceed with the course!)